﻿using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using TestCluster.usermodels;
using Volo.Abp.AspNetCore.Mvc;

namespace TestCluster.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    public class IBaseController : AbpController
    {
        /// <summary>
        /// 
        /// </summary>
        protected readonly ITestClusterDbContext _dbContext;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dbContext"></param>
        public IBaseController(ITestClusterDbContext dbContext)
        {
            _dbContext = dbContext;
        }
        /// <summary>
        /// 获取登录者UID
        /// </summary>
        /// <returns></returns>
        protected int CurrentUserId()
        {
            //time_uid_guid
            if (base.HttpContext.Request.Headers.ContainsKey(PublicString.TokenHeadName))
            {
                var token = base.HttpContext.Request.Headers[PublicString.TokenHeadName].ToString();

                //校验加密
                if (token.Contains("_"))
                {
                    var strs = token.Split('_');
                    if (strs.Length == 3)
                    {
                        var time = strs[0];
                        int.TryParse(strs[1], out var userid);
                        var temp = strs[2];
                        if ($"{time}_{userid}_{PublicString.TokenKey}".ToMd5Lower() == temp)
                        {
                            return userid;
                        }
                    }
                }
            }
            //临时测试，后续改成0
            return 0;
        }

        /// <summary>
        /// 获取登录者UID
        /// </summary>
        /// <returns></returns>
        protected string CurrentUserToken()
        {
            //time_uid_guid
            if (base.HttpContext.Request.Headers.ContainsKey(PublicString.TokenHeadName))
            {
                var token = base.HttpContext.Request.Headers[PublicString.TokenHeadName].ToString();
                //校验加密
                if (token.Contains("_"))
                {
                    var strs = token.Split('_');
                    if (strs.Length == 3)
                    {
                        var time = strs[0];
                        int.TryParse(strs[1], out var userid);
                        var temp = strs[2];
                        if ($"{time}_{userid}_{PublicString.TokenKey}".ToMd5Lower() == temp)
                        {
                            return token;
                        }
                    }
                }
            }
            //临时测试，后续改成0
            return "";
        }

        /// <summary>
        /// 检查并获取登录者ID，会抛出401异常
        /// </summary>
        /// <returns></returns>
        /// <exception cref="TestClusterException"></exception>
        protected int CheckAndReadUserId()
        {
            var find = false;
            //time_uid_guid
            if (base.HttpContext.Request.Headers.ContainsKey(PublicString.TokenHeadName))
            {
                var token = base.HttpContext.Request.Headers[PublicString.TokenHeadName].ToString();

                //校验加密
                if (token.Contains("_"))
                {
                    var strs = token.Split('_');
                    if (strs.Length == 3)
                    {
                        var time = strs[0];
                        int.TryParse(strs[1], out var userid);
                        var temp = strs[2];
                        if ($"{time}_{userid}_{PublicString.TokenKey}".ToMd5Lower() == temp)
                        {
                            find = true;
                            return userid;
                        }
                    }
                }
            }
            //临时测试，后续改成0
            if (!find)
            {
                throw new TestClusterException("当前未登录，请先登录后再试！", ExceptionCode.UnAuth);
            }
            else
            {
                return 0;
            }
        }

        /// <summary>
        /// 我的部门列表
        /// </summary>
        /// <returns></returns>
        protected List<PartInfoListDto> MyPartList()
        {
            var userid = CurrentUserId();
            if (userid != 0)
            {
                var list = from a in _dbContext.BindUserPart.Where(x => x.UserId == userid)
                           join b in _dbContext.PartInfo on a.PartId equals b.Id into c
                           from d in c.DefaultIfEmpty()
                           select new PartInfoListDto
                           {
                               Id = d.Id,
                               Name = d.Name,
                               Desc = d.Desc
                           };
                return list.ToList();
            }
            else
            {
                return new List<PartInfoListDto>();
            }
        }

        /// <summary>
        /// 获取UserInfo信息，有监听
        /// </summary>
        /// <returns></returns>
        protected UserInfo BaseCurrentUserInfo(int userid = 0)
        {
            if (userid == 0)
            {
                return _dbContext.UserInfo.Where(x => x.Id == CheckAndReadUserId()).FirstOrDefault();
            }
            else
            {
                return _dbContext.UserInfo.Where(x => x.Id == userid).FirstOrDefault();
            }
        }

    }
}
